﻿using System;
using System.Linq;
using System.Text;
using Demo.Framework.Datastructures;

namespace Demo.Framework.Datastructures
{
    public class Stack<T>
    {
        private LinkedList<T> _stack;

        public Stack()
        {
            _stack = new LinkedList<T>();
        }

        public bool Push(T value)
        {
            try
            {
                if (_stack.IsEmpty())
                    _stack.Insert(0, value);
                else
                {
                    var current = _stack.GetHead();
                    while (current.Next != null)
                    {
                        current = current.Next;
                    }
                    current.Next = new Node<T>(value);
                }
                return true;
            }
            catch (Exception)
            {                
                return false;
            }            
        }

        public T Pop()
        {
            if (_stack.IsEmpty())
                throw new Exception("The  stack is already empty");
            T deletedItem;
            var current = _stack.GetHead();

            if (current.Next == null)
            {
                deletedItem = _stack.Remove(0);
            }
            else
            {
                while (current.Next.Next != null)
                {
                    current = current.Next;
                }
                deletedItem = current.Next.Value;
                current.Next = null;
            }               
            return deletedItem;
        }

        public bool IsEmpty()
        {
            return _stack.IsEmpty();
        }

        public override string ToString()
        {
            return _stack.ToString();
        } 

    }
}
